#!/bin/bash

# 工程实践平台启动脚本
# 使用方法: ./scripts/start.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查脚本是否在项目根目录运行
check_project_root() {
    if [[ ! -f "pom.xml" ]] && [[ ! -f "docker-compose.yml" ]]; then
        log_error "请在项目根目录运行此脚本"
        exit 1
    fi
}

# 检查Docker服务状态
check_docker() {
    log_info "检查Docker服务状态..."
    
    if ! docker info &> /dev/null; then
        log_error "Docker服务未启动"
        echo "请启动Docker服务:"
        echo "  Linux: sudo systemctl start docker"
        echo "  Windows/macOS: 启动Docker Desktop"
        exit 1
    fi
    
    log_success "Docker服务运行正常"
}

# 检查项目构建状态
check_build_status() {
    log_info "检查项目构建状态..."
    
    if [[ ! -f "target/demo02-*.jar" ]]; then
        log_warning "项目未构建，正在构建..."
        if command -v mvn &> /dev/null; then
            mvn clean package -DskipTests
            log_success "项目构建完成"
        else
            log_error "Maven未安装，请先安装Maven"
            exit 1
        fi
    else
        log_success "项目已构建"
    fi
}

# 准备应用文件
prepare_app() {
    log_info "准备应用文件..."
    
    # 复制JAR文件到项目根目录
    JAR_FILE=$(find target -name "demo02-*.jar" | head -n 1)
    if [[ -n "$JAR_FILE" ]]; then
        cp "$JAR_FILE" app.jar
        log_success "应用文件准备完成: app.jar"
    else
        log_error "未找到构建的JAR文件"
        exit 1
    fi
}

# 启动MySQL服务
start_mysql() {
    log_info "启动MySQL服务..."
    
    # 检查MySQL容器是否已运行
    if docker ps | grep -q practice-platform-mysql; then
        log_info "MySQL服务已在运行"
        return 0
    fi
    
    # 创建MySQL数据目录
    mkdir -p mysql-data
    
    # 启动MySQL容器
    docker run -d \
        --name practice-platform-mysql \
        --restart unless-stopped \
        -e MYSQL_ROOT_PASSWORD=root \
        -e MYSQL_DATABASE=practice_platform \
        -e MYSQL_USER=practice_user \
        -e MYSQL_PASSWORD=practice_pass \
        -p 3306:3306 \
        -v "$(pwd)/mysql-data:/var/lib/mysql" \
        mysql:5.7 \
        --default-authentication-plugin=mysql_native_password
    
    log_success "MySQL服务启动完成"
    
    # 等待MySQL启动
    log_info "等待MySQL启动..."
    sleep 30
    
    # 检查MySQL连接
    if docker exec practice-platform-mysql mysql -u root -proot -e "SELECT 1;" &> /dev/null; then
        log_success "MySQL连接正常"
    else
        log_warning "MySQL连接检查失败，继续启动应用"
    fi
}

# 启动主应用
start_main_app() {
    log_info "启动主应用..."
    
    # 检查应用是否已在运行
    if [[ -f "app.pid" ]]; then
        PID=$(cat app.pid)
        if kill -0 $PID 2>/dev/null; then
            log_warning "应用已在运行 (PID: $PID)"
            return 0
        else
            rm -f app.pid
        fi
    fi
    
    # 创建日志目录
    mkdir -p logs
    
    # 启动应用
    nohup java -jar app.jar --spring.profiles.active=prod > logs/app.log 2>&1 &
    echo $! > app.pid
    
    log_success "主应用启动完成，PID: $(cat app.pid)"
}

# 等待应用启动
wait_for_app() {
    log_info "等待应用启动..."
    
    local max_attempts=30
    local attempt=1
    
    while [[ $attempt -le $max_attempts ]]; do
        if curl -s http://localhost:8080/actuator/health &> /dev/null; then
            log_success "应用启动成功！"
            return 0
        fi
        
        echo -n "."
        sleep 2
        ((attempt++))
    done
    
    log_error "应用启动超时"
    return 1
}

# 显示服务状态
show_service_status() {
    log_info "服务状态检查..."
    
    echo
    echo "=========================================="
    echo "服务状态"
    echo "=========================================="
    
    # 检查主应用
    if [[ -f "app.pid" ]]; then
        PID=$(cat app.pid)
        if kill -0 $PID 2>/dev/null; then
            echo "✅ 主应用: 运行中 (PID: $PID)"
            echo "   端口: 8080"
            echo "   日志: logs/app.log"
        else
            echo "❌ 主应用: 未运行"
        fi
    else
        echo "❌ 主应用: 未运行"
    fi
    
    # 检查MySQL
    if docker ps | grep -q practice-platform-mysql; then
        echo "✅ MySQL: 运行中"
        echo "   端口: 3306"
        echo "   用户名: root"
        echo "   密码: root"
        echo "   数据库: practice_platform"
    else
        echo "❌ MySQL: 未运行"
    fi
    
    echo "=========================================="
}

# 显示访问信息
show_access_info() {
    echo
    echo "=========================================="
    echo "访问信息"
    echo "=========================================="
    echo "主应用:     http://localhost:8080"
    echo "用户管理:   http://localhost:8080/user-management.html"
    echo "健康检查:   http://localhost:8080/actuator/health"
    echo "=========================================="
}

# 显示管理命令
show_management_commands() {
    echo
    echo "=========================================="
    echo "管理命令"
    echo "=========================================="
    echo "查看状态:   ./scripts/status.sh"
    echo "停止服务:   ./scripts/stop.sh"
    echo "查看日志:   tail -f logs/app.log"
    echo "重启应用:   ./scripts/restart.sh"
    echo "=========================================="
}

# 主函数
main() {
    echo "=========================================="
    echo "工程实践平台启动脚本"
    echo "=========================================="
    echo
    
    # 检查环境
    check_project_root
    check_docker
    check_build_status
    
    # 准备应用
    prepare_app
    
    # 启动服务
    start_mysql
    start_main_app
    
    # 等待启动
    if wait_for_app; then
        # 显示状态和信息
        show_service_status
        show_access_info
        show_management_commands
        
        log_success "平台启动完成！"
    else
        log_error "平台启动失败，请检查日志"
        echo "查看日志: tail -f logs/app.log"
        exit 1
    fi
}

# 执行主函数
main "$@" 